<?php
class comParser extends BasicModel {
	// флаги выхода из парсера
	const FINISH	= 1;
	const STOP		= 2;
	const ERROR		= 3;
	// массив страниц
	private $Pages;
	// массив спарсенного элемента
	private $Item;
	// классы
	private $WebLoader, $DOMParser, $Config, $Timer, $Language;
	// лог
	private $Log;

	/**
	 * Конструктора
	 */
	function __construct(Core $Site, $ComponentConfig) {
		parent::__construct($Site);
		$this->WebLoader	= new WebLoader();
		$this->DOMParser	= new DOMParser();
		$this->Timer			= new Timer();
		$this->Config			= $ComponentConfig;
		$this->Pages			= array ();
		$this->Item				= NULL;
		$this->Log				= array (
			'START_TIME'	=> '',
			'WORK_FLAG'		=> self::FINISH,
			'WORK_MSG'		=> array ()
		);
		$this->TodayWeather = NULL;
	}
	/**
	 * Запуск парсера
	 * @return type
	 */
	function Start() {
		// onliner
		$this->Pages = $this->WebLoader->Get('http://catalog.onliner.by/tv/listview/~add=0~sort_by=best~dir=asc~where=actual~currency=USD~city=minsk');
		if (is_string($this->Pages)) {
			$this->Language = new OnlinerLNG();
			$this->DOMParser->setHTML($this->Pages);
			$tvsArray = $this->DOMParser->Get('table.pltable a.pln')->toArray();
			for ($iTV = 0; $iTV < $tvsArray['childs']['length']; ++$iTV) {
				if ($iTV == 20) {return 0;}
				$TV = &$tvsArray['childs'][$iTV];
				$this->Pages = $this->WebLoader->Get('http://catalog.onliner.by/'.$TV['href']);
				if (is_string($this->Pages)) {
					$this->Item = array (
						'options' => array()
					);
					$this->parseOptions();
				}
			}
		}
		return 0;
	}
	/**
	 * Все характеристики с Onliner.by
	 * @return int
	 *
	function TVOption() {
		$this->DOMParser->setHTML($this->Pages);
		$OptArray = $this->DOMParser->Get('table.pdtable tr.pline2')->toArray();
		for ($iOpt = 0; $iOpt < $OptArray['childs']['length']; ++$iOpt) {
			$Option = &$OptArray['childs'][$iOpt];
			fwrite($this->F, $Option['childs'][0]['childs'][0]['text'].';');
			fwrite($this->F, ($Option['childs'][1]['text']?$Option['childs'][1]['text']:$Option['childs'][1]['childs'][0]['alt']).";\n");
		}
		return 0;
	}*/
	/**
	 * Запись лога
	 */
	private function WriteLog() {
		$Errors = ob_get_contents();
		ob_end_flush();
		$FOpen = fopen(LOGS_PATH.'com.weather_parser('.date('Y-m-d').').txt', 'a');
		fwrite($FOpen, "---------------------------------\n");
		fwrite($FOpen, "PARSER_LOG\n");
		fwrite($FOpen, "[START]=[".$_GET['start']."]\n");
		fwrite($FOpen, "[END]=[".$_GET['end']."]\n");
		fwrite($FOpen, "[START_TIME]=[".$this->Log['START_TIME']."]\n");
		//fwrite($FOpen, "[WORK_FLAG]=[".$this->Log['WORK_FLAG']."]\n");
		if (isset($this->Log['WORK_MSG'][0])) {
			foreach ($this->Log['WORK_MSG'] as $Index => $MSG) {
				fwrite($FOpen, "[MSG_".$Index."]=[".$MSG."]\n");
			}
		}
		fwrite($FOpen, "[ERRORS]=[");
		fwrite($FOpen, $Errors);
		fwrite($FOpen, "]\n---------------------------------\n");
		fclose($FOpen);
		return 0;
	}
	private function parseOptions() {
		$this->DOWParser->setHTML($this->Pages);
		$OptArray = $this->DOMParser->Get('table.pdtable tr.pline2')->toArray();
		$A	= array('TYPE', 'RESOLUTION', 'LIGHT_MATRIX', 'RATIO', 'T3D', 'COLOR', 'AUDIO');
		$C	= array('BLUETOOTH', 'P2P', 'SKYPE', 'S_VIDIO', 'WEB_TV', 'WiIFI_READY', 'ANTI_GLARE', 'QUICK_VIEW', 'HEADPHONE', 'WEB_BROWSER', 'RADIO', 'CLIENT', 'LINE_AUDIO', 'AD_SERVICES', 'PODCASTS', 'PROG_SCNA', 'SERVER', 'THX', 'ONE_CONTROL', 'T24P', 'DLNA', 'SCAN_TECH', 'SD_HD', 'FIRM_LIGHT', 'BACKLIGHT', 'RSS');
		$I	= array('DIAGONAL', 'T3D_GLASS', 'VGA', 'DVI', 'ETHERNET', 'HDMI', 'PC_AUDIO_IN', 'USB', 'AUDIO_OUT', 'V_VIEW', 'WEIGHT', 'RESP_TIME', 'RESP_TIME_GTG', 'HEIGHT', 'DEPTH', 'H_VIEW', 'RELEASE_Y', 'DYNAMIC_CONT', 'N_CHANNELS', 'CONTRAST', 'POVER_WORK', 'POVER_STAND', 'GRAIN_SIZE', 'SUBWOOFER', 'TELETEXT', 'TICKNESS_PANEL', 'V_ANGLE', 'H_ANGLE', 'FREQ_SWEEP', 'WIDTH', 'BRIGHTNESS', 'COMPOSIT_IN', 'COMPONENT_IN');
		$MA = array('TV_TUNNER', 'CI', 'WIFI', 'HDMI', 'IMAGES', 'CODECS', 'CONTAINERS', 'USE_USB', 'OTHER_FORMATS', 'SUBTITLES', 'S_PDIF_OUT', 'S_PDIF_IN');
		$T	= array('WEB_TV', 'ANTI_GLARE', 'AUDIO_OUT', 'AUDIO', 'DECODERS', 'ECOLOGY', 'C_C_C', 'DESCRIPTION', 'STAND', 'IMAGE_PROCESSOE', 'T24P', 'SCAN_TECH', 'T3D_EMITTER', 'SD_HD', 'FIRM_LIGHT', 'FRIM_OPTIONS', 'BACKLIGHT', 'PHOTO_CATALOGS', 'DIG_SOUND');
		$D	= array('T3D', 'CI', 'VGA', 'DVI', 'BLUETOOTH', 'ETHERNET', 'HDMI', 'PC_AUDIO_IN', 'SKYPE', 'S_VIDIO', 'TV_TUNNER', 'USB', 'WIFI', 'WEIGHT', 'HEIGHT', 'DEPTH', 'COMPOSIT_IN', 'COMPONENT_IN', 'USE_USB', 'PROG_SCNA', 'DLNA');
		for ($iOpt = 0; $iOpt < $OptArray['childs']['length']; ++$iOpt) {
			// свойство и значение
			$Option = &$OptArray['childs'][$iOpt]['childs'][0]['childs'][0];
			$OValue = array (
				'text'	=> (isset($OptArray['childs'][$iOpt]['childs'][1]['text']))?$OptArray['childs'][$iOpt]['childs'][1]['text']:'',
				'alt'		=> (isset($OptArray['childs'][$iOpt]['childs'][1]['childs'][0]['alt']) && $OptArray['childs'][$iOpt]['childs'][1]['childs'][0]['alt'] == 'Да')?1:NULL
			);
			// интекс свойства
			$Index = NULL;
			// поиск свойства
			foreach ($this->Language->Options as $Ind => $Val) {
				if (mb_stripos($Option['text'], $Val) !== FALSE) {
					$Index = $Ind;
					break;
				}
			}
			if (!is_null($Index)) {
				// ствойства тиа, a
				if (in_array($Index, $A)) {
					$ArrayName = $Index.'Array';
					$OptI = NULL;
					if ($Index == 'T3D') {$OptI = 1;}
					foreach ($this->Language->$ArrayName as $Ind => $Val) {
						if (mb_stripos($OValue['text'], $Val) !== FALSE) {
							$OptI = $Ind;
						}
					}
					if (!is_null($OptI)) {$this->Item['options'][$Index] = $OptI;}
				} // свойства типа, i
				elseif (in_array($Index, $I)) {
					if ($OValue['text'] != '' || isset($OValue['alt'])) {
						$Value = NULL;
						if (isset($OValue['alt'])) {$Value = 1;}
						if ($OValue['text'] != '') {
							if ($Index == 'T3D_GLASS') {
								preg_match('/([0-9]+)/si', $OValue['text'], $pValue);
								if (isset($pValue[1])) {$Value = $pValue[1];}
							} elseif($Index == 'HDMI') {
								preg_match_all('([0-9]+)', $OValue['text'], $pValue);
								if (isset($pValue[1][0])) {
									if (isset($pValue[1][2])) {
										$Value = $pValue[1][1] + $pValue[1][2];
									} else {$Value = $pValue[1][0] + $pValue[1][1];}
								}
							} elseif($Index == 'DYNAMIC_CONT' || $Index == 'CONTRAST') {
								$pValue = explode(':', $OValue['text']);
								$pValue = preg_replace('/([^0-9\.]+)/si', '', $pValue[0]);
								if (strlen($pValue) > 0) {$Value = $pValue;}
							} elseif($Index == 'VESA') {
								$pValue = explode('x', $OValue['text']);
								if (strlen($pValue[0]) > 0) {$Value = $pValue[0];}
							} else {
								if (preg_match('/([0-9\.]+)/si', $OValue['text'], $pValue)) {
									if (isset($pValue[1]) && strlen($pValue[1]) > 0) {$Value = $pValue[1];}
								}
							}
						}
						if (!is_null($Value)) {$this->Item['options'][$Index] = $Value;}
					}
				} // свойства типа, ma
				elseif (in_array($Index, $MA)) {
					$ArrayName = $Index.'Array';
					$Value = array();
					foreach ($this->Language->$ArrayName as $Ind => $Val) {
						if (mb_stripos($OValue['text'], $Val)) {
							$Value[] = $Ind;
						}
					}
					if (!empty($Value)) {$this->Item['options'][$Index] = implode(',', $Value);}
				} // свойства типа, с
				elseif (in_array($Index, $C)) {
					if (isset($OValue['alt'])) {$this->Item['options'][$Index] = 1;}
				} // свойства типа, d
				if (in_array($Index, $D)) {
					if (!empty($OValue['text']) && strlen($OValue['text']) > 0) {
						if (preg_match('/(\(.+?\))/si', $OValue['text'], $pValue)) {
							if (isset($pValue[1]) && strlen($pValue) > 0) {$this->Item['options'][$Index.'_T'] = $OValue['text'];}
						}
					}
				} // свойства типа, t
				elseif (in_array($Index, $T)) {
					if (strlen($OValue['text']) > 0) {$this->Item['options'][$Index] = $OValue['text'];}
				}
			}
		}
		var_dump($this->Item['options']);
	}
}
?>